package com.xuef.dxf.namenode.server;

import com.sun.org.apache.bcel.internal.generic.FNEG;
import com.xuef.dfs.namenode.rpc.model.HeartbeatRequest;
import com.xuef.dfs.namenode.rpc.model.HeartbeatResponse;
import com.xuef.dfs.namenode.rpc.model.RegisterRequest;
import com.xuef.dfs.namenode.rpc.model.RegisterResponse;
import com.xuef.dfs.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.stub.StreamObserver;

public class NameNodeRpcServiceImpl extends NameNodeServiceGrpc.NameNodeServiceImplBase {
    FSNameSystem fsNameSystem;
    DataNodeManager dataNodeManager;

    public NameNodeRpcServiceImpl(FSNameSystem fsNameSystem, DataNodeManager dataNodeManager) {
        this.dataNodeManager = dataNodeManager;
        this.fsNameSystem = fsNameSystem;
    }

    public boolean mkdir(String path){
        return fsNameSystem.mkdir(path);
    }


    @Override
    public void heartbeat(HeartbeatRequest request, StreamObserver<HeartbeatResponse> responseObserver) {
        dataNodeManager.heartbeat(new DataNodeInfo(request.getIp(), request.getHostname()));
        HeartbeatResponse response = HeartbeatResponse.newBuilder().
                setStatus(1).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    /**
     * 接受 DataNode 注册
     */
    @Override
    public void register(RegisterRequest request, StreamObserver<RegisterResponse> responseObserver) {
        dataNodeManager.registerDataNode(new DataNodeInfo(request.getIp(), request.getHostname()));
        RegisterResponse response = RegisterResponse.newBuilder().
                setStatus(1).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

}
